//
//  NewestViewController.m
//  PCNews
//
//  Created by PengchengWang on 16/3/2.
//  Copyright © 2016年 pengchengWang. All rights reserved.
//

#import "NewestViewController.h"
#import "DetailViewController.h"


#define kLastID 0
@interface NewestViewController ()<UITableViewDataSource,UITableViewDelegate,WMLoopViewDelegate>

@end

@implementation NewestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBeginViews];
    [self loopImagesBound];
    [self dataBound];
    [self setViews];
    
}

-(void)setBeginViews{
    self.lastID = kLastID;
    self.upImagesUrl = kNewsLoopImageURL;
}

///绑定轮播图数据
-(void)loopImagesBound{
    [URLRequestManager requestUrlWithType:GET strURL:self.upImagesUrl condition:nil success:^(id item) {
        NSArray *arr = item;
        self.arrImages = [NSMutableArray arrayWithCapacity:arr.count];
        self.arrTitle = [NSMutableArray arrayWithCapacity:arr.count];
        for (NSDictionary *dic in arr) {
            [self.arrImages addObject:[NSString stringWithFormat:@"%@",[dic valueForKey:@"icon"]]];
            [self.arrTitle addObject:[NSString stringWithFormat:@"%@",[dic valueForKey:@"title"]]];
            [self.upImageUrls addObject:[NSString stringWithFormat:@"http://m.mydrivers.com/app/newsdetail.aspx?id=%@&ver=1.1",[dic valueForKey:@"id"]]];
        }
        if (arr.count>1) {
            [self setLoopImages];
        }
        else{
            [self setOneTopImage];
        }
    }
       faile:^(NSError *error) {
       }];
}

-(void)setOneTopImage{
    self.topImageView =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 150)];
    [self.topImageView sd_setImageWithURL:[NSURL URLWithString:self.arrImages[0]]];
    
    self.tableV.tableHeaderView = self.topImageView;
    UIView * blackView =[[UIView alloc]initWithFrame:CGRectMake(0,130 , kScreenWidth, 20)];
    blackView.backgroundColor=[UIColor colorWithWhite:0.5 alpha:0.3];
    UILabel * lable =[[UILabel alloc]initWithFrame:CGRectMake(2, 2, kScreenWidth, 17)];
    lable.text =self.arrTitle[0];
    lable.textColor = [UIColor whiteColor];
    [blackView addSubview:lable];
    [self.topImageView addSubview:blackView];
    self.tableV.tableHeaderView =self.topImageView;
    [self.topImageView addSubview:blackView];
    self.tableV.tableHeaderView =self.topImageView;
    self.topImageView.userInteractionEnabled = YES;
    [self.topImageView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageTapAction)]];
    
}

-(void)imageTapAction{
    DetailViewController *detailVC = [[DetailViewController alloc]initWithDetailUrl:self.upImageUrls[0]];
    [self.navigationController pushViewController:detailVC animated:YES];
}

///绑定tableView数据
-(void)dataBound{
    //创建请求第几页的数据URL
    NSString *urlStr = [NSString stringWithFormat:@"http://m.mydrivers.com/app/newslist.aspx?tid=0&minId=%ld&ver=2.1&temp=141077031699.344391",(long)self.lastID];
    [URLRequestManager requestUrlWithType:GET strURL:urlStr condition:nil success:^(id item) {
        //当请求到最后一条数据ID为"0"时,证明请求第一组数据,清空大数组
        if (self.lastID == kLastID) {
            self.arrAllData = nil;
        }
        for (NSDictionary *dic in item) {
            BaseModel *model = [[BaseModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.arrAllData addObject:model];
        }
        //取得当前获取到的数组中最后一条数据的ID,作为请求下一组数据的参数(接口文档要求)
        BaseModel *model = self.arrAllData[self.arrAllData.count-1];
        self.lastID = model.id;
        [self.tableV reloadData];
        
        [self endRefresh];
    } faile:^(NSError *error) {
        [self endRefresh];
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"您的网络不给力!";
        [hud hide: YES afterDelay: 2];
    }];
}

-(void)endRefresh{
    
    [self.tableV.mj_header endRefreshing];
    [self.tableV.mj_footer endRefreshing];
}

-(void)setViews{
    self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-60) style:(UITableViewStylePlain)];
    [self.tableV registerNib:[UINib nibWithNibName:@"NewsTableViewCell" bundle:nil] forCellReuseIdentifier:@"NewsTableViewCell"];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    self.tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.lastID = kLastID;
        [self dataBound];
    }];
    
    self.tableV.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self dataBound];
    }];
}

-(void)setLoopImages{
    self.tableV.showsVerticalScrollIndicator = NO;
    WMLoopView *loopView = [[WMLoopView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, kUpImageHeight) images:self.arrImages titleText:self.arrTitle autoPlay:YES delay:2];
    loopView.delegate = self;
    self.tableV.tableHeaderView = loopView;
}

-(void)loopViewDidSelectedImage:(WMLoopView *)loopView index:(int)index{
    DetailViewController *detailVC = [[DetailViewController alloc]initWithDetailUrl:self.upImageUrls[index]];
    [self.navigationController pushViewController:detailVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.arrAllData count];
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsTableViewCell" forIndexPath:indexPath];
    BaseModel *model = self.arrAllData[indexPath.row];
    cell.lblTitle.text = model.title;
    cell.lblReviewcount.text = [NSString stringWithFormat:@"%@",model.reviewcount];
    [cell.imageV sd_setImageWithURL:[NSURL URLWithString:model.icon]];
    NSDateFormatter *postDateFormatter = [[NSDateFormatter alloc]init];
    [postDateFormatter setDateFormat:@"yyyy/M/d HH:mm:ss"];
    NSDate *postDate = [postDateFormatter dateFromString:model.postdate];
    NSDate *currentDate = [NSDate date];
    NSTimeInterval currentInterval = [currentDate timeIntervalSinceDate:postDate];
    NSTimeInterval dayInterval = 12*60*60;
    NSTimeInterval hourInterval = 60*60;
    NSMutableString *strEditorPostDate = model.editor.mutableCopy;
    if (currentInterval>dayInterval) {
        currentInterval = currentInterval/dayInterval;
        [strEditorPostDate appendString:[NSString stringWithFormat:@" | %.0f天前",currentInterval]];
    }else if (currentInterval>hourInterval && currentInterval<dayInterval){
        currentInterval = currentInterval/hourInterval;
        [strEditorPostDate appendString:[NSString stringWithFormat:@" | %.0f小时前",currentInterval]];
    }else{
        currentInterval = currentInterval/60;
        [strEditorPostDate appendString:[NSString stringWithFormat:@" | %.0f分钟前",currentInterval]];
    }
    cell.lblEditorAndPostdate.text = strEditorPostDate;
    if (model.stress.length) {
        NSString *strColor = [model.stress substringFromIndex:6];
        UIColor *stressColer = [ColorWithHex colorWithHexString:strColor alpha:1];
        cell.lblTitle.textColor = stressColer;
    }else {
        cell.lblTitle.textColor = [UIColor blackColor];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BaseModel *model = self.arrAllData[indexPath.row];
    NSString *strDetailUrl =[NSString stringWithFormat:@"http://m.mydrivers.com/app/newsdetail.aspx?id=%ld&ver=1.1",model.id];
    DetailViewController *detailVC = [[DetailViewController alloc]initWithDetailUrl:strDetailUrl];
    [self.navigationController pushViewController:detailVC animated:YES];
}



- (NSMutableArray *)arrAllData
{
    if (nil == _arrAllData) {
        _arrAllData = [[NSMutableArray alloc]init];
    }
    return _arrAllData;
}

-(NSMutableArray *)upImageUrls{
    if (_upImageUrls == nil) {
        _upImageUrls = [[NSMutableArray alloc]init];
    }
    return _upImageUrls;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
